{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 值计数和唯一值\n",
        "\n",
        "本教程详细介绍 Pandas 中的值计数和唯一值相关方法：value_counts, unique, nunique, mode。\n",
        "\n",
        "## 目录\n",
        "1. value_counts() - 值计数\n",
        "2. unique() - 唯一值\n",
        "3. nunique() - 唯一值数量\n",
        "4. mode() - 众数\n",
        "5. 综合应用\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 导入库\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "import warnings\n",
        "warnings.filterwarnings('ignore')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. value_counts() - 值计数\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`value_counts()` 统计每个值出现的次数。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)\n",
        "```\n",
        "\n",
        "**主要参数:**\n",
        "- `normalize`: 是否返回比例而非计数，默认 False\n",
        "- `sort`: 是否按值排序，默认 True\n",
        "- `ascending`: 是否升序排序，默认 False\n",
        "- `bins`: 是否分箱，默认 None\n",
        "- `dropna`: 是否排除NaN，默认 True\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回排序后的计数结果\n",
        "- ✅ 适用于分类数据\n",
        "- ✅ 可以返回比例或计数\n",
        "\n",
        "**适用场景:** 数据分布分析、频率统计、分类统计\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 创建示例数据\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "df = pd.DataFrame({\n",
        "    '部门': ['技术', '销售', '人事', '技术', '销售', '技术', '人事', '技术', '销售', '人事'],\n",
        "    '学历': ['本科', '硕士', '本科', '硕士', '博士', '本科', '硕士', '本科', '硕士', '本科'],\n",
        "    '绩效': ['A', 'B', 'A', 'B', 'A', 'B', 'A', 'B', 'A', 'B'],\n",
        "    '年龄': [25, 30, 28, 32, 35, 27, 29, 31, 33, 28]\n",
        "})\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(df)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例2: 基础值计数\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 统计各部门出现次数\n",
        "print(\"各部门值计数:\")\n",
        "print(df['部门'].value_counts())\n",
        "print(\"\\n统计学历值计数:\")\n",
        "print(df['学历'].value_counts())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例3: 返回比例\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 返回比例而非计数\n",
        "print(\"各部门比例 (normalize=True):\")\n",
        "print(df['部门'].value_counts(normalize=True))\n",
        "print(\"\\n各部门计数:\")\n",
        "print(df['部门'].value_counts(normalize=False))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. unique() - 唯一值\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`unique()` 返回唯一值的数组。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.unique()\n",
        "```\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回唯一值数组\n",
        "- ✅ 保持原始顺序（首次出现顺序）\n",
        "- ✅ 适用于Series\n",
        "\n",
        "**适用场景:** 获取唯一值列表\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 获取唯一值\n",
        "print(\"部门的唯一值:\")\n",
        "print(df['部门'].unique())\n",
        "print(\"\\n学历的唯一值:\")\n",
        "print(df['学历'].unique())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. nunique() - 唯一值数量\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`nunique()` 返回唯一值的数量。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.nunique(dropna=True)\n",
        "```\n",
        "\n",
        "**主要参数:**\n",
        "- `dropna`: 是否排除NaN，默认 True\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回唯一值数量（整数）\n",
        "- ✅ 适用于Series和DataFrame\n",
        "- ✅ 可以设置是否包含NaN\n",
        "\n",
        "**适用场景:** 统计唯一值数量、数据多样性\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 统计唯一值数量\n",
        "print(\"各部门唯一值数量:\")\n",
        "print(df['部门'].nunique())\n",
        "print(\"\\n各列唯一值数量:\")\n",
        "print(df.nunique())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. mode() - 众数\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`mode()` 返回众数（出现频率最高的值）。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.mode(axis=0, numeric_only=False, dropna=True)\n",
        "```\n",
        "\n",
        "**主要参数:**\n",
        "- `axis`: 0(按列) 或 1(按行)，默认 0\n",
        "- `numeric_only`: 是否只计算数值型列，默认 False\n",
        "- `dropna`: 是否排除NaN，默认 True\n",
        "\n",
        "**特点:**\n",
        "- ✅ 返回众数（可能多个）\n",
        "- ✅ 适用于Series和DataFrame\n",
        "- ✅ 如果有多个众数，返回所有\n",
        "\n",
        "**适用场景:** 查找最常见的值、数据分布分析\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 计算众数\n",
        "print(\"部门的众数:\")\n",
        "print(df['部门'].mode())\n",
        "print(\"\\n各列的众数:\")\n",
        "print(df.mode())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. 综合应用\n",
        "\n",
        "### 示例4: 处理缺失值\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建包含缺失值的数据\n",
        "df2 = pd.DataFrame({\n",
        "    '部门': ['技术', '销售', '人事', '技术', np.nan, '销售', '技术', np.nan]\n",
        "})\n",
        "\n",
        "print(\"包含缺失值的数据:\")\n",
        "print(df2)\n",
        "print(\"\\n值计数 (dropna=True, 默认):\")\n",
        "print(df2['部门'].value_counts(dropna=True))\n",
        "print(\"\\n值计数 (dropna=False):\")\n",
        "print(df2['部门'].value_counts(dropna=False))\n",
        "print(\"\\n唯一值数量 (dropna=True):\")\n",
        "print(df2['部门'].nunique(dropna=True))\n",
        "print(\"\\n唯一值数量 (dropna=False):\")\n",
        "print(df2['部门'].nunique(dropna=False))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例5: 分箱统计\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 对数值型数据分箱后计数\n",
        "print(\"年龄分箱统计 (bins=3):\")\n",
        "print(df['年龄'].value_counts(bins=3, sort=False))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 总结\n",
        "\n",
        "**值计数和唯一值方法总结:**\n",
        "1. ✅ **value_counts()**: 统计每个值出现的次数（可返回比例）\n",
        "2. ✅ **unique()**: 返回唯一值数组（保持原始顺序）\n",
        "3. ✅ **nunique()**: 返回唯一值数量（整数）\n",
        "4. ✅ **mode()**: 返回众数（出现频率最高的值）\n",
        "\n",
        "**最佳实践:**\n",
        "- 使用 `value_counts()` 了解数据分布和频率\n",
        "- 使用 `unique()` 获取唯一值列表\n",
        "- 使用 `nunique()` 快速统计唯一值数量\n",
        "- 使用 `mode()` 查找最常见的值\n",
        "- 注意 NaN 值的处理（dropna参数）\n",
        "- 使用 `normalize=True` 获取比例而非计数\n"
      ]
    }
  ],
  "metadata": {
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
